
package com.kugou.game.sdk.utils;

import com.kugou.game.sdk.entity.MessageInfo;
import com.kugou.game.sdk.receiver.PushMessageReceiver;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.utils.SimpleImageLoader.ImageCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.RemoteViews;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：处理推送消息的辅助类
 * 
 * @author zhj
 * @since 2015-1-13
 */
public class PushMessageHelper {
    // 通知栏
    private NotificationManager mNotificationManager = null;

    private static PushMessageHelper mHelper;

    private Context mContext;

    private Message mMessage;

    private PushMessageHelper(Context context) {
        mContext = context;
        mHandler = new MyHandler(mContext.getMainLooper(), this);
    };

    public static PushMessageHelper getInstance(Context context) {
        if (mHelper == null) {
            mHelper = new PushMessageHelper(context);
        }
        return mHelper;
    }

    public void handlePushMessage(String str) {
        mMessage = Message.obtain(mHandler);
        mMessage.obj = str;
        mMessage.sendToTarget();
    }

    // 将json字符串解析成messageinfo
    private MessageInfo getMessageInfoFromJson(String str) {
        JSONObject itemObj;
        MessageInfo info = null;
        try {
            info = new MessageInfo();
            itemObj = new JSONObject(str);
            info.setContent(itemObj.getString("content"));
            info.setDownloadUrl(itemObj.getString("downloadurl"));
            info.setImageUrl(itemObj.getString("imageurl"));
            info.setMessageId(itemObj.getString("messageid"));
            info.setPackagename(itemObj.getString("packagename"));
            info.setTitle(itemObj.getString("title"));
            info.setType(itemObj.getString("type"));
            int type = Integer.parseInt(info.getType());
            if (type == 3) {
                ArrayList<String> list = new ArrayList<String>();
                JSONArray array = itemObj.getJSONArray("extend1");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject obj = array.getJSONObject(i);
                    list.add(obj.getString("packagename"));
                }
                info.setPackageNames(list);
            } else if (type == 4) {
                info.setContentUrl(itemObj.getString("extend1"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return info;
    }

    private Handler mHandler;

    @SuppressWarnings("deprecation")
    void buildNotification(final MessageInfo info) {
        this.mNotificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        final Notification notification = new Notification(Rx.drawable.kg_pushmsg_icon,
                info.getTitle(), System.currentTimeMillis());
        // 放置在"正在运行"栏目中
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        // 设置默认声音
        notification.defaults |= Notification.DEFAULT_SOUND;
        // 设定震动(需加VIBRATE权限)
        notification.defaults |= Notification.DEFAULT_VIBRATE;

        final RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
                Rx.layout.kg_message_notify_layout);

        contentView.setTextViewText(Rx.id.kg_message_tv_title, info.getTitle());
        contentView.setTextViewText(Rx.id.kg_message_tv_content, info.getContent());

        // 指定个性化视图
        notification.contentView = contentView;

        Intent intent = getIntentByMessageInfo(info);
        // 如果消息类型处理不了，则不进行通知操作
        if (intent == null)
            return;

        int messageId = Integer.parseInt(info.getMessageId());
        // 通知栏被点击时，先通知广播，发送统计数据
        Intent clickIntent = new Intent(mContext, PushMessageReceiver.class);
        clickIntent.setAction(PushMessageReceiver.ACTION_RECEIVE_NOTIFICATION_CLICK);
        clickIntent.putExtra(PushMessageReceiver.INTENT_EXTRA_INTENT, intent);
        clickIntent.putExtra(PushMessageReceiver.INTENT_EXTRA_MESSAGEID, messageId);
        PendingIntent contentIntent = PendingIntent.getBroadcast(mContext,
                Integer.parseInt(info.getMessageId()), clickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        // 指定内容意图
        notification.contentIntent = contentIntent;
        // 下载图标
        new SimpleImageLoader().loadDrawable(info.getImageUrl(), new ImageCallback() {

            @Override
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                if (imageDrawable != null) {
                    contentView.setImageViewBitmap(Rx.id.kg_message_iv,
                            ((BitmapDrawable) imageDrawable).getBitmap());
                    mNotificationManager.notify(Integer.parseInt(info.getMessageId()), notification);
                }
            }
        });
        mNotificationManager.notify(Integer.parseInt(info.getMessageId()), notification);

        // 发送统计 - 显示推送消息
        StaticsManager.sendPushMessageStatics(StatCmd.CMD_BI_PUSHMESSAGE_RECEIVED, messageId);
    }

    // 根据消息类型创建不同的intent
    private Intent getIntentByMessageInfo(MessageInfo info) {
        Intent intent = null;
        // 判断当前是消息类型
        if (info.getType().equals("1") || info.getType().equals("3")) {
            // 无条件下载
            intent = new Intent(Intent.ACTION_VIEW);
            Uri content_url = Uri.parse(info.getDownloadUrl());
            intent.setData(content_url);
        } else if (info.getType().equals("2")) {
            intent = new Intent();
            // 回流
            PackageManager packageManager = mContext.getPackageManager();
            try {
                intent = packageManager.getLaunchIntentForPackage(info.getPackagename());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (info.getType().equals("4")) {
            // 打开链接
            intent = new Intent(Intent.ACTION_VIEW);
            Uri content_url = Uri.parse(info.getContentUrl());
            intent.setData(content_url);
        }
        return intent;
    }

    static class MyHandler extends Handler {

        private WeakReference<PushMessageHelper> wr;

        public MyHandler(Looper looper, PushMessageHelper helper) {
            super(looper);
            wr = new WeakReference<PushMessageHelper>(helper);
        }

        @Override
        public void handleMessage(Message msg) {
            PushMessageHelper helper = wr.get();
            String jstr = (String) msg.obj;
            MessageInfo info = helper.getMessageInfoFromJson(jstr);
            if (info == null)
                return;
            if (info.getType().equals("1")) {// 如果是下载类型
                // 检测当前是否已经安装该应用,如果已经安装就不显示推送通知
                if (!helper.isAvilible(info.getPackagename())) {
                    helper.buildNotification(info);
                }
            } else if (info.getType().equals("2")) {// 如果是回流
                // 检测当前是否已经安装该应用
                if (helper.isAvilible(info.getPackagename())) {
                    // 如果当前已经安装了要回流的应用，并且该应用配置为显示
                    helper.buildNotification(info);
                }
            } else if (info.getType().equals("3")) {// 指定游戏下载
                // 如果安装了要下载的游戏，则不处理此消息
                if (helper.isAvilible(info.getPackagename()))
                    return;

                List<String> list = info.getPackageNames();
                if (list != null && list.size() > 0) {
                    for (String packagename : list) {
                        if (helper.isAvilible(packagename)) {
                            helper.buildNotification(info);
                            break;
                        }
                    }
                }
            } else if (info.getType().equals("4")) {// 打开链接
                helper.buildNotification(info);
            }
        }
    }

    // 检测应用是否安装
    private boolean isAvilible(String packageName) {
        final PackageManager packageManager = mContext.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    public Context getContext() {
        return mContext;
    }

}
